import kivy

from kivy.clock import Clock
from kivy.properties import NumericProperty
from kivy.properties import ListProperty

from ui.fittable_widgets import FittableLabel


class LongPressLabel(FittableLabel):
    time_press_sec = NumericProperty(.5)
    enable_color = ListProperty([.1, .1, .8, 1])

    __events__ = ('on_long_press',)

    def __init__(self, **kwargs):
        super(LongPressLabel, self).__init__(**kwargs)
        self.register_event_type('on_long_press')
        self.def_color = self.color
        self.time_sec = .0
        self.time_stop = False
        self.is_drag_out = False

    def start_clock(self, dt):
        if self.time_stop or self.is_drag_out:
            return False
        self.time_sec += dt
        if self.time_sec >= self.time_press_sec:
            self.time_stop = True
            self.color = self.enable_color

    def on_touch_down(self, touch):
        if not self.collide_point(*touch.pos):
            return
        self.is_drag_out = False
        self.time_sec = .0
        self.time_stop = False
        Clock.schedule_interval(self.start_clock, 0.02)

    def on_touch_up(self, touch):
        self.color = self.def_color
        self.is_drag_out = True
        if not self.collide_point(*touch.pos):
            return
        if self.time_stop:
            self.dispatch('on_long_press')

    def on_touch_move(self, touch):
        if not self.collide_point(*touch.pos):
            self.color = self.def_color
            self.is_drag_out = True
            self.time_stop = False

    def on_long_press(self):
        pass
